<template>
  <a-modal title="提现" :footer="false" title-align="start" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="900">
    <div>
      <span>当前可提现金额</span>
      <span>￥{{ $extract(props.accountInfo, 'withdrawWalletAccount.availabeBalance') }}</span>
    </div>
    <div>最小提现金额 200元，每月最多可提现2次</div>
    <a-space>
      <a-input-number v-model="amountVal" hide-button placeholder="请输入提现金额，只能输入整数" style="width: 250px">
        <template #prefix> ￥ </template>
      </a-input-number>
      <a-button class="gray-outline" @click="confirmQuestion" :disabled="$extract(props.accountInfo, 'withdrawWalletAccount.availabeBalance') == 0">提交提现请求</a-button>
    </a-space>

    <div>
      <span style="color: red">收款账户</span>
      <span class="cursor" style="margin-left: 2px" @click="showInput = true">
        <icon-edit />
      </span>
    </div>

    <div style="color: red">
      <a-space v-if="!showInput">
        <span>卡号：{{ $extract(backInfo, 'bankAccountNumber') ? $extract(backInfo, 'bankAccountNumber') : '--' }}</span>
        <span>支行：{{ $extract(backInfo, 'bankBranchName') ? $extract(backInfo, 'bankBranchName') : '--' }}</span>
        <span>名称：{{ $extract(backInfo, 'bankAccountName') ? $extract(backInfo, 'bankAccountName') : '--' }}</span>
      </a-space>
      <a-form ref="formRef" :model="form" auto-label-width v-else>
        <a-space>
          <a-form-item label="卡号" field="bankAccountNumber" :rules="[{ required: true, message: '请输入卡号' }]">
            <a-input v-model="form.bankAccountNumber" />
          </a-form-item>
          <a-form-item label="支行" field="bankBranchName" :rules="[{ required: true, message: '请输入支行' }]">
            <a-input v-model="form.bankBranchName" />
          </a-form-item>
          <a-form-item label="名称" field="bankAccountName" :rules="[{ required: true, message: '请输入名称' }]">
            <a-input v-model="form.bankAccountName" />
          </a-form-item>
          <a-form-item hide-label>
            <a-button type="primary" :loading="submitLoading" @click="submit">保存</a-button>
            <a-button class="gray-outline ml10" @click="showInput = false">取消</a-button>
          </a-form-item>
        </a-space>
      </a-form>
    </div>

    <a-steps type="arrow" :current="0" :class="[!showInput ? 'mt10' : '', 'mb10']">
      <a-step>提交提现请求</a-step>
      <a-step> 平台审批，12小时内完成审批 </a-step>
      <a-step>审批通过12小时完成转账</a-step>
    </a-steps>

    <ul class="tab-box">
      <li :class="[curIndex == index ? 'active' : '', 'cursor']" v-for="(item, index) of tabList" :key="item" @click="tabClick(index)">{{ item }}</li>
    </ul>

    <a-table size="mini" class="table-two-line mt10" :data="dataList" @sorter-change="sortChange" :loading="loading" :pagination="false" :scroll="{ y: 400 }">
      <template #columns>
        <a-table-column title="提交时间" #cell="{ record, rowIndex }" :width="140" data-index="gmtCreate" :sortable="{ sortDirections: ['ascend', 'descend'] }">
          {{ $setTime(record.gmtCreate) }}
        </a-table-column>
        <a-table-column title="转账金额" #cell="{ record, rowIndex }" :width="100" data-index="amount" :sortable="{ sortDirections: ['ascend', 'descend'] }"> ￥{{ record.amount }} </a-table-column>
        <a-table-column title="提交人" #cell="{ record, rowIndex }" :width="80">
          {{ record.createUname }}
        </a-table-column>
        <a-table-column title="收款账号" :width="160">
          <template #cell="{ record, rowIndex }">
            <div>卡号：{{ record.bankAccountNumber }}</div>
            <div>支行：{{ record.bankBranchName }}</div>
            <div>名称：{{ record.bankAccountName }}</div>
          </template>
        </a-table-column>
        <a-table-column title="审批时间" v-if="[1, 2].includes(curIndex)" #cell="{ record, rowIndex }" :width="140" data-index="gmtCheck" :sortable="{ sortDirections: ['ascend', 'descend'] }">
          {{ $setTime(record.gmtCheck) }}
        </a-table-column>
        <a-table-column title="转账日期" v-if="curIndex == 2" #cell="{ record, rowIndex }" :width="140" data-index="gmtWithdraw" :sortable="{ sortDirections: ['ascend', 'descend'] }">
          {{ $setTime(record.gmtWithdraw) }}
        </a-table-column>
        <a-table-column title="转账附件" v-if="curIndex == 2" #cell="{ record, rowIndex }" :width="80">
          <ImgPopover :src="item" v-for="(item, index) in record.attachmentUrlList" :key="index">
            <template #con>
              <div style="width: 40px; height: 40px">
                <a-image :preview="false" width="40" height="40" :src="item" />
              </div>
            </template>
          </ImgPopover>
        </a-table-column>
        <a-table-column title="驳回原因" #cell="{ record, rowIndex }" :width="80" v-if="curIndex == 3">
          <!-- {{ rowIndex + 1 }} -->
          <TextLimit position="top" :rows="2" :val="record.rejectReason"></TextLimit>
        </a-table-column>
        <a-table-column title="单据号" #cell="{ record, rowIndex }" :width="80">
          {{ record.docNumber }}
        </a-table-column>
        <a-table-column title="操作" #cell="{ record, rowIndex }" :width="60" v-if="curIndex == 0">
          <a-button type="text" @click="cancel(record)">取消提现</a-button>
        </a-table-column>
      </template>
    </a-table>
    <div class="pagination-footer" style="margin: 10px 0 0">
      <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { submitWithdrawRequest, getBlanKAccountByCompanyId, saveOrUpdateBatchById, findCompanyWithdrawRequestPage, cancelWithdrawRequest } from '@/api/finance/wallet'
  import useUserStore from '@/store/modules/user'

  let props = defineProps(['modelValue', 'accountInfo', 'initAccount'])
  let emits = defineEmits(['update:modelValue', 'save'])
  const formRef = ref()
  const statusMap = {
    0: 'APPROVAL',
    1: 'PENDING',
    2: 'COMPLETED',
    3: 'REJECTED',
  }
  const userInfo = useUserStore()
  let dataList = ref([])
  let amountVal = ref()
  let backInfo = ref()
  let loading = ref(false)
  let showInput = ref(false)
  let submitLoading = ref(false)
  let pageNation = ref({ total: 0, pageSize: 20, pageNum: 1 })
  let searchValue: any = ref({
    sortField: 'gmtCreate',
    sortAsc: false,
  })
  let tabList = ref(['待审批', '待转账', '完成转账', '已驳回'])
  let curIndex = ref(0)
  let form: any = ref({})
  let showvisible: any = computed({
    set(val) {
      emits('update:modelValue', val)
    },
    get() {
      return props.modelValue
    },
  })
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }
  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }
  const getList = async () => {
    const params = {
      ...searchValue.value,
      status: statusMap[curIndex.value],
      accountId: `${props.accountInfo.withdrawWalletAccount.id}`,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    if (!params.sortField) {
      params.sortField = 'gmtCreate'
      params.sortAsc = false
    }
    loading.value = true
    const res: any = await findCompanyWithdrawRequestPage(params)
    if (res) {
      dataList.value = res?.data?.records || []
      pageNation.value.total = res.data.total
    }
    loading.value = false
  }
  const tabClick = (index: number) => {
    curIndex.value = index
    pageNation.value.pageNum = 1
    getList()
  }
  const submit = async () => {
    const valid = await formRef.value.validate()
    if (!valid) {
      let params = {
        ...form.value,
        id: backInfo.value.id,
      }
      const res: any = await saveOrUpdateBatchById([params])
      if (res) {
        Message.success('保存成功')
        form.value = {}
        formRef.value.resetFields()
        formRef.value.clearValidate()
        showInput.value = false
        getBackInfo()
      }
    }
  }
  const confirmQuestion = async () => {
    if (!amountVal.value) return Message.error('请输入金额')
    if (!backInfo.value.bankAccountNumber) return Message.error('请先完善收款账户信息')
    let params = {
      accountId: props.accountInfo.withdrawWalletAccount.id,
      amount: amountVal.value,
      bankAccountName: backInfo.value.bankAccountName,
      bankAccountNumber: backInfo.value.bankAccountNumber,
      bankBranchName: backInfo.value.bankBranchName,
      withdrawMonth: 2,
    }
    const res: any = await submitWithdrawRequest(params)
    if (res) {
      Message.success('提现申请提交成功')
      getList()
      props.initAccount()
      amountVal.value = ''
    }
  }

  const getBackInfo = async () => {
    const res: any = await getBlanKAccountByCompanyId({ companyId: userInfo.companyId })
    backInfo.value = res?.data || {}
    form.value = res?.data || {}
  }

  const cancel = async (item: any) => {
    const res: any = await cancelWithdrawRequest({ id: item.id })
    if (res) {
      Message.success('取消成功')
      props.initAccount()
      getList()
    }
  }

  onMounted(() => {
    getBackInfo()
    getList()
  })
</script>

<style lang="less" scoped>
  .tab-box {
    display: flex;
    li {
      height: 30px;
      width: 60px;
      text-align: center;
      line-height: 30px;
      border: 1px solid #d7d7d7;
      border-right: none;
      &:last-child {
        border-right: 1px solid #d7d7d7;
      }
      font-size: 12px;
    }
    .active {
      background: #165dff;
      color: white;
    }
  }
</style>
